<?php
/*dbloginstatus.php*/
$user;
$session_id;
$time_out = 120;

function checkStatus() {
	global $time_out;
	$uid;
	global $user, $session_id;
	$valid=false;
	
	
	$remote_ip = $_SERVER['REMOTE_ADDR'];
	$con = mysql_connect('localhost','root','') or die(mysql_error());
	mysql_select_db("sistema", $con) or die(mysql_error());
	
	
	$res = mysql_query("select user_id, session_id, status, time_to_sec(timediff(now(), last_access)) as duration from session_log where remote_ip='$remote_ip' and session_id=(select max(session_id) from session_log where remote_ip='$remote_ip');", $con)  or die(mysql_error());
	if(mysql_num_rows($res) == 0) {
		//print("<center><h1>Invalid Session!</h1><br />");
		mysql_close($con);
		/*print("<a href='index.html'>Go to Login Page</a></center>");
		exit(0);*/
		header("Location: index.php");
	}

	$session_id = mysql_result($res,0,"session_id");
	$uid = mysql_result($res, 0, "user_id");
	$d = mysql_result($res,0,"duration");
	$n=mysql_num_rows($res);
	$st=mysql_result($res,0,"status");
	
	if($st == "EXPIRED") {
		//print("<center><h1>Invalid Session!</h1><br />");
		mysql_close($con);
		/*print("<a href='index.html'>Go to Login Page</a></center>");
		exit(0);*/
		header("Location: index.php");
	}
	else if($d > $time_out) {
		/*print("<center><h1>Session timed out!</h1><h3>" . ($d/60) . " minutes after last access!<br />(time limit is " . ($time_out/60) . " minutes)</h3><br />");*/
		$res = mysql_query("select @m:=max(session_id) from session_log where remote_ip='$remote_ip';", $con);
		$res = mysql_query("update session_log set status=2 where remote_ip='$remote_ip' and session_id=@m;", $con)  or die(mysql_error());
		mysql_close($con);
		/*print("<a href='index.html'>Go to Login Page</a></center>");
		exit(0);*/
		header("Location: index.php");
	}

	mysql_query("update session_log set last_access=now() where remote_ip='$remote_ip' and session_id=$session_id;", $con)  or die(mysql_error());
	$res=mysql_query("select nome_completo from usuarios where idusuarios=$uid;",$con);
	$user=mysql_result($res, 0, "nome_completo");
	mysql_close($con);
	return true;
}
checkStatus();/*
if(checkStatus()) {
	printf("<center><b>Welcome %s! Your id is: %s</b><br />",$user,$session_id);
	printf("<a href='dblogout.php'>Logout %s</a></center>",$user);
}*/
?>